#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

void Usage(std::string proc) {
    std::cerr << "Usage: " << "\n\t" << proc << " dest_ip dest_port" << std::endl;
}

// ./usp_client dest_ip dest_port
int main(int argc, char *argv[]) {
    if (argc != 3){
        Usage(argv[0]);
        return 1;
    }
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0) {
        std::cout << "socket error" << std::endl;
        return 1;
    }
    // client不需要明确bind
    char buffer[1024];
    for ( ; ; ) {
        std::cout << "[test@VM-4-13-centos udp]$ ";
        fflush(stdout);
        buffer[0] = 0;
        struct sockaddr_in dest;
        memset(&dest, 0, sizeof(dest));
        dest.sin_family = AF_INET;
        dest.sin_port  = htons(std::stoi(argv[2]));
        dest.sin_addr.s_addr = inet_addr(argv[1]);
        ssize_t s = read(0, buffer, sizeof(buffer)-1);
        if (s > 0) {
            buffer[s - 1] = 0;
            //std::cout << buffer << std::endl;
            sendto(sockfd, buffer, strlen(buffer), 0,(struct sockaddr*)&dest, sizeof(dest));
            buffer[0] = 0;
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            ssize_t s = recvfrom(sockfd, buffer, sizeof(buffer)-1, 0, (struct sockaddr*)&peer, &len);
            if (s > 0) {
                buffer[s] = 0;
                std::cout << "echo# " <<  buffer << std::endl;
            }
        }
    }
    
    close(sockfd);
    return 0;
}
